<template>
  <view class="p-[24rpx] bg-white rounded-[16rpx] shadow-sm">
    <text class="block font-bold mb-2"><text class="text-red-500">*</text> 期望上门时间：</text>
    <!-- 开始日期时间 -->
    <view class="flex items-center justify-between mb-[24rpx] p-[16rpx] bg-[#f8fafc] rounded-[12rpx]">
      <text class="text-[24rpx] font-semibold text-[#374151]">开始时间</text>
      <view class="flex items-center gap-[12rpx]">
        <view
          class="px-[20rpx] py-[12rpx] bg-white rounded-[8rpx] border border-[#e5e7eb] active:bg-[#f3f4f6] transition-colors"
          @tap="showStartCalendar">
          <text class="text-[24rpx] text-[#6b7280]">{{ startDate || '选择日期' }}</text>
        </view>
        <view
          class="px-[20rpx] py-[12rpx] bg-white rounded-[8rpx] border border-[#e5e7eb] active:bg-[#f3f4f6] transition-colors"
          @tap="showStartTimePicker">
          <text class="text-[24rpx] text-[#6b7280]">{{ startTime || '选择时间' }}</text>
        </view>
      </view>
    </view>

    <!-- 结束日期时间 -->
    <view class="flex items-center justify-between mb-[24rpx] p-[16rpx] bg-[#f8fafc] rounded-[12rpx]">
      <text class="text-[24rpx] font-semibold text-[#374151]">结束时间</text>
      <view class="flex items-center gap-[12rpx]">
        <view
          class="px-[20rpx] py-[12rpx] bg-white rounded-[8rpx] border border-[#e5e7eb] active:bg-[#f3f4f6] transition-colors"
          @tap="showEndCalendar">
          <text class="text-[24rpx] text-[#6b7280]">{{ endDate || '选择日期' }}</text>
        </view>
        <view
          class="px-[20rpx] py-[12rpx] bg-white rounded-[8rpx] border border-[#e5e7eb] active:bg-[#f3f4f6] transition-colors"
          @tap="showEndTimePicker">
          <text class="text-[24rpx] text-[#6b7280]">{{ endTime || '选择时间' }}</text>
        </view>
      </view>
    </view>

    <!-- 开始日期日历弹窗 -->
    <nut-calendar v-model:visible="startCalendarVisible" :default-value="startCalendarValue" :start-date="startDate"
      :end-date="endDate" @choose="onStartCalendarChoose" @close="startCalendarVisible = false" />

    <!-- 结束日期日历弹窗 -->
    <nut-calendar v-model:visible="endCalendarVisible" :default-value="endCalendarValue" :start-date="startDate"
      :end-date="endDate" @choose="onEndCalendarChoose" @close="endCalendarVisible = false" />

    <!-- 开始时间选择弹窗 -->
    <nut-popup v-model:visible="startTimePickerVisible" position="bottom" round>
      <view class="p-[24rpx]">
        <view class="text-center mb-[16rpx]">
          <text class="text-[32rpx] font-semibold text-[#374151]">选择开始时间</text>
        </view>
        <nut-picker v-model="startTimeValue" :columns="timeOptions" @confirm="onStartTimeConfirm"
          @cancel="startTimePickerVisible = false" />
      </view>
    </nut-popup>

    <!-- 结束时间选择弹窗 -->
    <nut-popup v-model:visible="endTimePickerVisible" position="bottom" round>
      <view class="p-[24rpx]">
        <view class="text-center mb-[16rpx]">
          <text class="text-[32rpx] font-semibold text-[#374151]">选择结束时间</text>
        </view>
        <nut-picker v-model="endTimeValue" :columns="timeOptions" @confirm="onEndTimeConfirm"
          @cancel="endTimePickerVisible = false" />
      </view>
    </nut-popup>

    <!-- 展示结果 -->
    <!-- <view v-if="startDate && startTime && endDate && endTime"
      class="mt-[16rpx] p-[20rpx] bg-gradient-to-r from-[#dbeafe] to-[#e0e7ff] rounded-[12rpx] border border-[#bfdbfe]">
      <view class="flex items-center justify-center">
        <text class="text-[30rpx] font-medium text-[#1e40af]">
          {{ startDate }} {{ startTime }} - {{ endDate }} {{ endTime }}
        </text>
      </view>
    </view> -->

    <!-- 根据时间段显示额外收费项目 -->
    <view v-if="startDate && startTime && endDate && endTime"
      class="mt-[16rpx] flex flex-col gap-2 bg-orange-50 p-[24rpx] rounded-[12rpx]">
      <text class="font-bold text-orange-600 text-[30rpx]">时间段额外收费：</text>
      <view class="flex justify-between" v-if="goodsStore.urgentFree && goodsStore.feeControl.urgent">
        <view class="flex items-center">
          <text class="text-[24rpx]">加急费：</text>
          <IconFont name="ask2" size="15" class="ml-1 text-[#999]" @tap="showUrgentFeeInfo = true" />
        </view>
        <text class="text-red-500 font-bold text-[24rpx]">¥{{ goodsStore.urgentFree }}</text>
      </view>
      <view class="flex justify-between" v-if="goodsStore.nightFree && goodsStore.feeControl.night">
        <view class="flex items-center">
          <text class="text-[24rpx]">夜班费：</text>
          <IconFont name="ask2" size="15" class="ml-1 text-[#999]" @tap="showNightFeeInfo = true" />
        </view>
        <text class="text-red-500 font-bold text-[24rpx]">¥{{ goodsStore.nightFree }}</text>
      </view>
      <view class="flex justify-between" v-if="goodsStore.festivalFree && goodsStore.feeControl.festival">
        <view class="flex items-center">
          <text class="text-[24rpx]">节假日费：</text>
          <IconFont name="ask2" size="15" class="ml-1 text-[#999]" @tap="showFestivalFeeInfo = true" />
        </view>
        <text class="text-red-500 font-bold text-[24rpx]">¥{{ goodsStore.festivalFree }}</text>
      </view>
      <view class="flex justify-between" v-if="goodsStore.overtimeFee">
        <view class="flex items-center">
          <text class="text-[24rpx]">超时费：</text>
          <IconFont name="ask2" size="15" class="ml-1 text-[#999]" @tap="showOvertimeFeeInfo = true" />
        </view>
        <text class="text-red-500 font-bold text-[24rpx]">¥{{ goodsStore.overtimeFee }}</text>
      </view>
      <view class="flex justify-between border-t pt-2 mt-2">
        <text class="font-bold text-[24rpx]">时间段费用小计：</text>
        <text class="text-red-500 font-bold text-[30rpx]">¥{{ getTotalTimeFee }}</text>
      </view>
    </view>
  </view>
  <nut-popup v-model:visible="showUrgentFeeInfo" position="center" :style="{ width: '80%' }">
    <view class="p-[32rpx] text-center">
      <text class="block text-[32rpx] font-bold mb-[16rpx]">加急费说明</text>
      <view class="text-[26rpx] text-[#666] mb-[16rpx]">加急费根据下单与期望上门时间间隔自动计算，具体以实际规则为准。</view>
      <view class="flex flex-col gap-[8rpx] items-center mb-[24rpx]">
        <view v-for="item in goodsStore.urgent.options" :key="item.name" class="flex justify-between w-[90%] bg-[#f8fafc] rounded-[8rpx] px-[16rpx] py-[8rpx] border border-[#e5e7eb]">
          <view class="text-[24rpx] text-left">{{ item.name }}</view>
          <view class="text-[24rpx] text-right text-orange-600 font-bold">¥{{ item.fee }}</view>
        </view>
      </view>
      <view class="flex justify-center mt-[24rpx]">
        <nut-button class="w-[200rpx]" type="primary" size="small" @tap="showUrgentFeeInfo = false">我知道了</nut-button>
      </view>
    </view>
  </nut-popup>
  <nut-popup v-model:visible="showNightFeeInfo" position="center" :style="{ width: '80%' }">
    <view class="p-[32rpx] text-center">
      <text class="block text-[32rpx] font-bold mb-[16rpx]">夜班费说明</text>
      <view class="text-[26rpx] text-[#666] mb-[32rpx]">夜班费适用于服务时间段内包含夜间时段（如18:00-06:00），具体以实际规则为准。</view>
      <view class="flex justify-center mt-[24rpx]">
        <nut-button class="w-[200rpx]" type="primary" size="small" @tap="showNightFeeInfo = false">我知道了</nut-button>
      </view>
    </view>
  </nut-popup>
  <nut-popup v-model:visible="showFestivalFeeInfo" position="center" :style="{ width: '80%' }">
    <view class="p-[32rpx] text-center">
      <text class="block text-[32rpx] font-bold mb-[16rpx]">节假日费说明</text>
      <view class="text-[26rpx] text-[#666] mb-[32rpx]">节假日费适用于服务时间段内包含法定节假日或周末，具体以实际规则为准。</view>
      <view class="flex justify-center mt-[24rpx]">
        <nut-button class="w-[200rpx]" type="primary" size="small" @tap="showFestivalFeeInfo = false">我知道了</nut-button>
      </view>
    </view>
  </nut-popup>
  <nut-popup v-model:visible="showOvertimeFeeInfo" position="center" :style="{ width: '80%' }">
    <view class="p-[32rpx] text-center">
      <text class="block text-[32rpx] font-bold mb-[16rpx]">超时费说明</text>
      <view class="text-[26rpx] text-[#666] mb-[32rpx]">超时费为服务超出工单时长部分所产生的费用。每超过1个工单时长需加收（不足1小时按1小时算）5公里内远程费+技术服务费。</view>
      <view class="flex justify-center mt-[24rpx]">
        <nut-button class="w-[200rpx]" type="primary" size="small" @tap="showOvertimeFeeInfo = false">我知道了</nut-button>
      </view>
    </view>
  </nut-popup>
</template>

<script setup>
import { ref, computed } from 'vue'
import dayjs from 'dayjs'
import isBetween from 'dayjs/plugin/isBetween'
import { useAuthStore, useGoodsStore } from '@/store';
import { getLastTimeStr, getListTimeStr } from './tooler';
import { matchTimeDifference } from '@/utils';
import { IconFont } from '@nutui/icons-vue-taro'


const goodsStore = useGoodsStore();

dayjs.extend(isBetween)

// 弹窗显示状态
const startCalendarVisible = ref(false)
const endCalendarVisible = ref(false)
const startTimePickerVisible = ref(false)
const endTimePickerVisible = ref(false)
const showUrgentFeeInfo = ref(false)
const showNightFeeInfo = ref(false)
const showFestivalFeeInfo = ref(false)
const showOvertimeFeeInfo = ref(false)

// 日期时间值
const startDate = ref('')
const startTime = ref('')
const endDate = ref('')
const endTime = ref('')

// 日历组件绑定值
const startCalendarValue = ref('')
const endCalendarValue = ref('')

// 时间选择器绑定值
const startTimeValue = ref(['08', '00'])
const endTimeValue = ref(['09', '00'])

// 夜班、节假日和加急费用标志
const nightFee = ref(false)
const holidayFee = ref(false)
const urgentFee = ref(0)

// 时间选项
const hourOptions = Array.from({ length: 24 }, (_, i) => {
  const h = i.toString().padStart(2, '0')
  return { text: h, value: h }
})
const minuteOptions = Array.from({ length: 12 }, (_, i) => {
  const m = (i * 5).toString().padStart(2, '0')
  return { text: m, value: m }
})
const timeOptions = ref([hourOptions, minuteOptions])

// 取 goodsStore 里的加急、夜班、节假日规则
const urgentOptions = goodsStore.urgent.options
const nightOptions = goodsStore.night.options
const nightFeeAmount = goodsStore.night.price || 0
const festivalFeeAmount = goodsStore.festival.fee || 0

// 检查夜班、节假日和加急费用
function checkFees(start, end) {
  // 1. 加急费（只和 start、now 有关）
  // const now = dayjs();
  // const hoursDiff = start.diff(now, 'minute', true) / 60;
  // urgentFee.value = 0;
  // for (const opt of urgentOptions) {
  //   if (hoursDiff >= (opt.min || 0) && hoursDiff < (opt.max || 9999)) {
  //     urgentFee.value = opt.fee;
  //     break;
  //   }
  // }

  let isHoliday = false
  let isNight = false

  // 2. 夜班费（只要时间段内有夜班时段）
  nightFee.value = false;
  let cur = start;
  while (cur.isBefore(end)) {
    const hour = cur.hour();
    if (hour >= 18 || hour < 6) {
      isNight = true;
      break;
    }
    cur = cur.add(1, 'hour');
  }

  // 3. 节假日费（只要时间段内有周六日）
  // holidayFee.value = false;
  let dayCursor = start.startOf('day');
  const endDay = end.startOf('day');
  while (dayCursor.isBefore(endDay) || dayCursor.isSame(endDay)) {
    const day = dayCursor.day();
    if (day === 0 || day === 6) {
      isHoliday = true;
      break;
    }
    dayCursor = dayCursor.add(1, 'day');
  }

  const {diffHours, matchedRecord} = matchTimeDifference(start.format('YYYY-MM-DD HH:mm'), goodsStore.urgent.options)
  if(matchedRecord){
    goodsStore.urgent.cur = goodsStore.urgent.options.find(item => item.name === matchedRecord.name)
  }

  console.log('[加急费计算] 最终 urgentFee:', matchedRecord)
  console.log('节假日:', isHoliday)
  console.log('夜班:', isNight)
  goodsStore.festival.choose = isHoliday
  goodsStore.isHoliday = isHoliday
  goodsStore.night.choose = isNight
  goodsStore.beginDate = start.format('YYYY-MM-DD HH:mm')
  goodsStore.endDate = end.format('YYYY-MM-DD HH:mm')
}

// 获取时间段总费用
const getTotalTimeFee = computed(() => {
  let total = 0

  // 加急费
  total += goodsStore.urgentFree || 0

  // 夜班费
  total += goodsStore.nightFree || 0


  total += goodsStore.festivalFree || 0

  // 超时费
  total += goodsStore.overtimeFee || 0

  return total
})

// 计算结束时间为开始时间+1小时
function setEndTimeAuto() {
  if (!startDate.value || !startTime.value) return
  const start = dayjs(`${startDate.value} ${startTime.value}`, 'YYYY-MM-DD HH:mm')
  if (!start.isValid()) {
    console.log('Invalid start time:', startDate.value, startTime.value)
    return
  }
  
  const end = start.add(goodsStore.duration||60, 'minute')
  endDate.value = end.format('YYYY-MM-DD')
  endTime.value = end.format('HH:mm')
  endTimeValue.value = [end.format('HH'), end.format('mm')]
  goodsStore.beginDate = start.format('YYYY-MM-DD HH:mm')
  goodsStore.endDate = end.format('YYYY-MM-DD HH:mm')
  checkFees(start, end)
}

// 显示开始日期日历
const showStartCalendar = () => {
  startCalendarVisible.value = true
}

// 显示结束日期日历
const showEndCalendar = () => {
  endCalendarVisible.value = true
}

// 显示开始时间选择器
const showStartTimePicker = () => {
  startTimePickerVisible.value = true
}

// 显示结束时间选择器
const showEndTimePicker = () => {
  endTimePickerVisible.value = true
}

// 开始日期选择
const onStartCalendarChoose = (param) => {
  startDate.value = param[3]
  startCalendarVisible.value = false
  setEndTimeAuto()
}

// 结束日期选择
const onEndCalendarChoose = (param) => {
  endDate.value = param[3]
  endCalendarVisible.value = false
  if (startDate.value && startTime.value && endDate.value && endTime.value) {
    const start = dayjs(`${startDate.value} ${startTime.value}`, 'YYYY-MM-DD HH:mm')
    const end = dayjs(`${endDate.value} ${endTime.value}`, 'YYYY-MM-DD HH:mm')
    if (end.isBefore(start)) {
      console.log('End time is before start time, resetting end time')
      setEndTimeAuto()
    } else {
      checkFees(start, end)
    }
  }
}

// 开始时间确认
const onStartTimeConfirm = ({ selectedValue }) => {
  const [hour, minute] = selectedValue
  startTime.value = `${hour}:${minute}`
  startTimeValue.value = [hour, minute]
  startTimePickerVisible.value = false
  setEndTimeAuto()
}

// 结束时间确认
const onEndTimeConfirm = ({ selectedValue }) => {
  const [hour, minute] = selectedValue
  endTime.value = `${hour}:${minute}`
  endTimeValue.value = [hour, minute]
  endTimePickerVisible.value = false
  if (startDate.value && startTime.value && endDate.value && endTime.value) {
    const start = dayjs(`${startDate.value} ${startTime.value}`, 'YYYY-MM-DD HH:mm')
    const end = dayjs(`${endDate.value} ${endTime.value}`, 'YYYY-MM-DD HH:mm')
    if (end.isBefore(start)) {
      console.log('End time is before start time, resetting end time')
      setEndTimeAuto()
    } else {
      checkFees(start, end)
    }
  }
}
</script>